/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 音乐项数据模型 - 支持多种数据源和缓存功能
 */

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';

/// 音乐项数据模型
/// 包含音乐的基本信息、播放源和缓存数据
class MusicItemModel {
  final String id;
  final String title;
  final String artist;
  final String artistId;
  final String album;
  final String albumId;
  final String? albumArt;
  final String audioUrl;
  final String sourceType;
  final String sourceUrl;
  final Duration? duration;
  final bool disabled;

  // UI 相关属性
  final List<TextSpan> titleSpans;
  final List<TextSpan> msgSpans;
  final List<Color> colorList;

  // 缓存相关属性
  final int? cachedDurationMs;
  final bool isPreloaded;
  final DateTime? preloadedAt;

  // AudioPlayer Source 对象
  final Source? source;

  const MusicItemModel({
    required this.id,
    required this.title,
    required this.artist,
    this.artistId = '',
    required this.album,
    this.albumId = '',
    this.albumArt,
    required this.audioUrl,
    this.sourceType = 'url',
    this.sourceUrl = '',
    this.duration,
    this.disabled = false,
    this.titleSpans = const [],
    this.msgSpans = const [],
    this.colorList = const [Colors.white, Colors.white],
    this.cachedDurationMs,
    this.isPreloaded = false,
    this.preloadedAt,
    this.source,
  });

  /// 从QQ音乐API数据创建MusicItemModel
  /// 适配QQ音乐的数据结构
  factory MusicItemModel.fromQQMusic(Map<String, dynamic> json) {
    // 处理歌手信息
    String artist = '';
    if (json['singer'] != null &&
        json['singer'] is List &&
        (json['singer'] as List).isNotEmpty) {
      artist = json['singer'][0]['name'] ?? '';
    }

    // 处理专辑封面
    String? albumArt;
    if (json['albummid'] != null && json['albummid'].toString().isNotEmpty) {
      albumArt =
          'https://y.gtimg.cn/music/photo_new/T002R300x300M000${json['albummid']}.jpg';
    }

    // 处理时长
    Duration? duration;
    if (json['interval'] != null) {
      duration = Duration(seconds: json['interval']);
    }

    return MusicItemModel(
      id: json['songmid']?.toString() ?? '',
      title: json['songname']?.toString() ?? '',
      artist: artist,
      artistId: json['singer']?[0]?['mid']?.toString() ?? '',
      album: json['albumname']?.toString() ?? '',
      albumId: json['albummid']?.toString() ?? '',
      albumArt: albumArt,
      audioUrl: '', // QQ音乐需要通过额外接口获取播放链接
      sourceType: 'qq_music',
      sourceUrl: json['strMediaMid']?.toString() ?? '',
      duration: duration,
      disabled: json['pay']?['payplay'] == 1, // QQ音乐付费歌曲标记
    );
  }

  /// 从通用JSON数据创建MusicItemModel
  /// 适配标准的JSON数据结构
  factory MusicItemModel.fromJson(Map<String, dynamic> json) {
    // 处理时长
    Duration? duration;
    if (json['duration'] != null) {
      if (json['duration'] is int) {
        duration = Duration(milliseconds: json['duration']);
      } else if (json['duration'] is String) {
        final durationMs = int.tryParse(json['duration']);
        if (durationMs != null) {
          duration = Duration(milliseconds: durationMs);
        }
      }
    }

    // 处理颜色列表
    List<Color> colorList = [Colors.white, Colors.white];
    if (json['colorList'] != null && json['colorList'] is List) {
      final colors = json['colorList'] as List;
      if (colors.length >= 2) {
        colorList = [
          Color(colors[0] ?? Colors.white.value),
          Color(colors[1] ?? Colors.white.value),
        ];
      }
    }

    return MusicItemModel(
      id: json['id']?.toString() ?? '',
      title: json['title']?.toString() ?? '',
      artist: json['artist']?.toString() ?? '',
      artistId: json['artistId']?.toString() ?? '',
      album: json['album']?.toString() ?? '',
      albumId: json['albumId']?.toString() ?? '',
      albumArt: json['albumArt']?.toString(),
      audioUrl: json['audioUrl']?.toString() ?? '',
      sourceType: json['sourceType']?.toString() ?? 'url',
      sourceUrl: json['sourceUrl']?.toString() ?? '',
      duration: duration,
      disabled: json['disabled'] == true,
      colorList: colorList,
      cachedDurationMs: json['cachedDurationMs'],
      isPreloaded: json['isPreloaded'] == true,
      preloadedAt: json['preloadedAt'] != null
          ? DateTime.tryParse(json['preloadedAt'])
          : null,
    );
  }

  /// 转换为JSON格式
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'artist': artist,
      'artistId': artistId,
      'album': album,
      'albumId': albumId,
      'albumArt': albumArt,
      'audioUrl': audioUrl,
      'sourceType': sourceType,
      'sourceUrl': sourceUrl,
      'duration': duration?.inMilliseconds,
      'disabled': disabled,
      'colorList': colorList.map((color) => color.value).toList(),
      'cachedDurationMs': cachedDurationMs,
      'isPreloaded': isPreloaded,
      'preloadedAt': preloadedAt?.toIso8601String(),
    };
  }

  /// 获取缓存的音频时长
  Duration? get cachedDuration => cachedDurationMs != null
      ? Duration(milliseconds: cachedDurationMs!)
      : null;

  /// 创建带有缓存时长的副本
  MusicItemModel copyWithCachedDuration(Duration duration) {
    return MusicItemModel(
      id: id,
      title: title,
      artist: artist,
      artistId: artistId,
      album: album,
      albumId: albumId,
      albumArt: albumArt,
      audioUrl: audioUrl,
      sourceType: sourceType,
      sourceUrl: sourceUrl,
      duration: this.duration,
      disabled: disabled,
      titleSpans: titleSpans,
      msgSpans: msgSpans,
      colorList: colorList,
      cachedDurationMs: duration.inMilliseconds,
      isPreloaded: isPreloaded,
      preloadedAt: preloadedAt,
      source: source,
    );
  }

  /// 创建标记为已预加载的副本
  MusicItemModel copyWithPreloadStatus({bool preloaded = true}) {
    return MusicItemModel(
      id: id,
      title: title,
      artist: artist,
      artistId: artistId,
      album: album,
      albumId: albumId,
      albumArt: albumArt,
      audioUrl: audioUrl,
      sourceType: sourceType,
      sourceUrl: sourceUrl,
      duration: duration,
      disabled: disabled,
      titleSpans: titleSpans,
      msgSpans: msgSpans,
      colorList: colorList,
      cachedDurationMs: cachedDurationMs,
      isPreloaded: preloaded,
      preloadedAt: preloaded ? DateTime.now() : null,
      source: source,
    );
  }

  /// 检查预加载是否过期
  /// [maxAge] 最大缓存时间，默认30分钟
  bool isPreloadExpired({Duration maxAge = const Duration(minutes: 30)}) {
    if (preloadedAt == null) return true;
    return DateTime.now().difference(preloadedAt!) > maxAge;
  }

  /// 获取显示用的艺术家名称
  String get displayArtist => artist.isEmpty ? '未知艺术家' : artist;

  /// 获取显示用的专辑名称
  String get displayAlbum => album.isEmpty ? '未知专辑' : album;

  /// 获取显示用的时长字符串
  String get durationText {
    final dur = duration ?? cachedDuration;
    if (dur == null) return '--:--';

    final minutes = dur.inMinutes;
    final seconds = dur.inSeconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is MusicItemModel && other.id == id;
  }

  @override
  int get hashCode => id.hashCode;

  @override
  String toString() {
    return 'MusicItemModel(id: $id, title: $title, artist: $artist, album: $album)';
  }
}
